package com.sh.data.engine.domain.authority.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sh.data.engine.domain.authority.service.TokenService;
import com.sh.data.engine.repository.dao.authority.UserTokenMapper;
import com.sh.data.engine.repository.dao.authority.entity.UserTokenEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.KeyGenerator;
import java.util.Base64;
import java.util.UUID;

@Service
@Slf4j
public class TokenServiceImpl implements TokenService {

    @Autowired
    private UserTokenMapper userTokenMapper;

    private static final String SECRET;

    static {
        try {
            KeyGenerator keyGen = KeyGenerator.getInstance("HmacSHA256");
            keyGen.init(256); // 初始化为256位
            SECRET = Base64.getEncoder().encodeToString(keyGen.generateKey().getEncoded());
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    @Override
    public String initToken(String userId) {
        UserTokenEntity userTokenEntity = new UserTokenEntity();
        userTokenEntity.setUserId(userId);
        String token = UUID.randomUUID().toString().replace("-", "");
//                Jwts.builder()
//                .setSubject(userId)
//                .setIssuedAt(new Date())
//                .signWith(SignatureAlgorithm.HS256, SECRET.getBytes())
//                .compact();
        userTokenEntity.setUserToken(token);
        userTokenMapper.insert(userTokenEntity);
        return token;
    }

    /**
     * 重置token
     */
    @Override
    public String resetToken(String userId) {
        //根据token查询tb_user_token的记录
        UserTokenEntity userTokenEntity = userTokenMapper.selectOne(new LambdaQueryWrapper<UserTokenEntity>()
                .eq(UserTokenEntity::getUserId, userId));
        String tokenNew = initToken(userId);
        userTokenEntity.setUserToken(tokenNew);
        userTokenMapper.update(userTokenEntity, new LambdaQueryWrapper<UserTokenEntity>().eq(UserTokenEntity::getUserId, userId));
        return tokenNew;
    }

    @Override
    public String getToken(String userId) {
        return userTokenMapper.selectOne(new LambdaQueryWrapper<UserTokenEntity>().eq(UserTokenEntity::getUserId, userId)).getUserToken();
    }
}